﻿using Microsoft.AspNetCore.Mvc;
using Quartz;
using TaskMasterByQuartz.Domain.InterfaceRepository;
using TaskMasterByQuartz.WebAPI.Controllers.Req;

namespace TaskMasterByQuartz.WebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SchedulerController : ControllerBase
    {
        private readonly ISchedulerCenter schedulerCenter;

        public SchedulerController(ISchedulerCenter schedulerCenter)
        {
            this.schedulerCenter = schedulerCenter;
        }

        [HttpPost]
        public void AddJob([FromBody] JobInfoReq entity)
        {
            schedulerCenter.AddScheduleJobAsync(
                entity.JobGroup,
                entity.JobName,
                entity.EndTime,
                entity.JobType,
                entity.RequestUrl,
                entity.Headers,
                entity.RequestParameters,
                entity.RequestType,
                entity.TriggerType,
                entity.Cron,
                entity.BeginTime,
                entity.RunTimes,
                entity.IntervalSecond,
                entity.Description
            );
        }

        /// <summary>
        /// 移除任务
        /// </summary>
        [HttpDelete]
        public void Remove(string group, string name)
        {
            schedulerCenter.DelScheduleJobAsync(group, name);
        }

        /// <summary>
        /// 立即执行
        /// </summary>
        /// <param name="job"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<bool> TriggerJob(string group, string name)
        {
            var j = new JobKey(name,group);
            await schedulerCenter.TriggerJobAsync(j);
            return true;
        }


        /// <summary>
        /// 恢复运行暂停的任务
        /// </summary> 
        /// <returns></returns>
        [HttpPost]
        public async void ResumeJob(string group, string name)
        {
            var jobKey = new JobKey(name, group);
            await schedulerCenter.ResumeJobAsync(group,name);
        }
    }
}
